package view;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Work;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/Download")
public class DownloadServlet extends Servlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws javax.servlet.ServletException,
			java.io.IOException {
		printPostPage(req, resp, null);
	};

	@Override
	void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		try {
			long id = Long.valueOf(request.getParameter("workId"));
			Work work = new Work(id);
			out.println("<form class='workInfo' action='Controller' method='POST'>");
			out.println("	<input type='hidden' name='workId' value='" + work.getId() + "'>");
			out.println("	<div class='title'>" + work.getTitle() + "</div></br>");
			out.println("	<div class='authorName'> Autor: " + work.getAuthorName() + "</div></br>");
			out.println("	<div class='theme'> Tema: " + work.getTheme() + "</div></br>");
			out.println("	<div class='category'> Categoria: " + work.getCategory().toString() + "</div></br>");
			out.println("	<div class='keyWords'> Palavras-chave: " + work.getKeyWordsString() + "</div></br>");
			out.println("	<div class='description'> Descrição: " + work.getDescription() + "</div></br>");
			out.println("	<input type='submit' name='button' value='Download'>");
			out.println("</form>");
		} catch (Exception ex) {
			out.println(HtmlFactory.createErrorMessage(ex.getMessage()));
		}
	}

	@Override
	void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		try {
			long id = Long.valueOf(request.getParameter("workId"));
			Work work = new Work(id);

			FileInputStream fis = work.prepareDownload();
			OutputStream os = response.getOutputStream();
			byte[] buffer = new byte[4096];
			int length;
			while ((length = fis.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			fis.close();
			os.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}